//
//  PlayerViewController.swift
//  Swift_MyLive
//
//  Created by admin on 16/9/8.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit



class PlayerViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
   /* @available(iOS 2.0, *)
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
    }*/

    
    var dataModel : DataModel?
    var superView : UIView?
    var playerItem : AVPlayerItem?
    var player : AVPlayer?
    var playerLayer : AVPlayerLayer?
    var timeLable : UILabel?
    var tbView : UITableView?
    var moreArray : NSMutableArray?
    var strId : String?
    var slider : UISlider?
    var link : CADisplayLink?
    var progress : UIProgressView?
    override func viewDidLoad() {
        
        moreArray = NSMutableArray()
        self.view.backgroundColor = UIColor.white
        
        
        self.setplayView()
        
        self.setTableView()
        self.loadData()
        
        
         self.link = CADisplayLink(target: self, selector: #selector(PlayerViewController.update))
        self.link!.add( to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
        
        self.title = dataModel?.title
        
       
        
    }
    
    func loadData()
    {
        let url = "http://suggest.cntvwb.cn/cntv-rec/recommend/0/1/1/C1809948-1C96-4397-944F-E94EE8FBF6B9/\(dataModel!.vid)"
        AppLicationInfo.shareInstance.POST(getUrl: url, parame: nil, isHead: false, success: { (data) in
            
            print(data)
            let dataArr = data.arrayForKey(key: "hotRes")
            for dic in dataArr
            {
                self.moreArray!.add(dic)
            }
            
            self.tbView?.reloadData()
            }) { (data, error) in
                
        }
    }

    func setTableView()
    {
        tbView = UITableView(frame: CGRect(x: 0, y: 300, width: WIDTH, height: HEIGHT-300-49))
        tbView?.delegate = self
        tbView?.dataSource = self
        tbView?.rowHeight = 70
        self.view.addSubview(tbView!)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.moreArray!.count
    }
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let ID = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        var imgVc : UIImageView?
        var lable : UILabel?
        if cell == nil {
            
            cell = UITableViewCell(style: .default, reuseIdentifier: ID)
            
            imgVc = UIImageView(frame: CGRect(x: 10, y: 10, width: 80, height: 60))
            cell?.contentView.addSubview(imgVc!)
            
            lable = UILabel(frame: CGRect(x: 90, y: 10, width: WIDTH-100, height: 60))
            lable?.numberOfLines = 0
            cell?.contentView.addSubview(lable!)
            
        }
        let dic = self.moreArray![indexPath.row] as! NSDictionary
        imgVc?.loadImgUrl( imgUrl: dic.stringForKey(key: "picUrl"))
  
        lable?.text = dic.stringForKey(key: "title")
        
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let dic = self.moreArray![indexPath.row] as! NSDictionary
        strId = dic.stringForKey(key: "id")
        self.removeRevce()
        self.setplayView()
        
    }
    
    func setDataM(dataM:DataModel)
    {
        dataModel = dataM;
    }
    
    func setplayView()
    {
       SVProgressHUD.show()
        superView = UIView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: 300))
        superView?.backgroundColor = UIColor.black
        self.view.addSubview(superView!)
        
        timeLable = UILabel(frame: CGRect(x: 10, y: 280, width: 200, height: 20))
        timeLable?.textColor = UIColor.white
//        timeLable?.backgroundColor = UIColor.red
        self.view.addSubview(timeLable!)

        
        progress = UIProgressView(frame:CGRect(x: 10, y: 270, width: WIDTH-20, height: 10))
        
        progress?.progressTintColor = UIColor.orange
        
        self.view.addSubview(progress!)
        
        slider = UISlider(frame: CGRect(x: 10, y: 266, width: WIDTH-20, height: 10))
        slider?.maximumTrackTintColor = UIColor.clear
        
//        slider?.backgroundColor = UIColor.purpleColor()
        slider?.addTarget(self, action: #selector(sliderTouchDown(slider:)), for: UIControlEvents.touchDown)

        slider!.addTarget(self, action: #selector(sliderTouchUpOut(slider:)), for: UIControlEvents.touchUpInside)
        slider!.addTarget(self, action: #selector(sliderChange(slider:)), for: UIControlEvents.valueChanged)
 
        slider?.isUserInteractionEnabled = false
         self.view!.addSubview(slider!)
        
        if strId == nil {
            
            strId = dataModel!.vid
        }

        
        let urlStr = "http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/\(strId!)/main.m3u8?maxbr=1200"
        
        let url = NSURL(string: urlStr)
        
        playerItem = AVPlayerItem(url:url! as URL)
        //监听缓冲进度
        playerItem?.addObserver(self, forKeyPath:"loadedTimeRanges", options:NSKeyValueObservingOptions.new, context:nil)
        //监听状态改变
        playerItem?.addObserver(self, forKeyPath:"status", options:NSKeyValueObservingOptions.new, context:nil)

        
        //将视频源赋值给播放对象
      self.player = AVPlayer(playerItem:playerItem!)
        
        //初始化视频显示layler
        playerLayer = AVPlayerLayer(player: player!)
        
        // 设置显示模式
        playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer!.contentsScale = UIScreen.main.scale
        
        
        playerLayer!.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 300)
        
        superView!.layer.addSublayer(playerLayer!)
        
        self.player!.play()

    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let playerItem = object as? AVPlayerItem else { return }
        if keyPath == "loadedTimeRanges"{
            // 缓冲进度 暂时不处理
            let items = playerItem.duration.value
            let miao = playerItem.duration.timescale
            
            //            let currentTime = CMTimeGetSeconds(self.player!.currentTime())
            
            let totalTime = TimeInterval(items) / TimeInterval(miao)
            
            let array = playerItem.loadedTimeRanges
            let timeRange = array.first?.timeRangeValue
            
            self.update()
            if timeRange != nil {
                
                let startSeconds = CMTimeGetSeconds(timeRange!.start)
                let durationSecound = CMTimeGetSeconds(timeRange!.duration)
                let result = startSeconds + durationSecound
                progress?.progress = Float(result/totalTime)
            }
            
        }else if keyPath == "status"{
            // 监听状态改变
            if playerItem.status == AVPlayerItemStatus.readyToPlay{
                // 只有在这个状态下才能播放
//                self.player!.play()
                print("正在播放")
                slider?.isUserInteractionEnabled = true
                SVProgressHUD.dismiss()
                
            }
        }
        else if playerItem.status == AVPlayerItemStatus.failed
        {
            SVProgressHUD.showError(withStatus: "加载异常！")
            self.dispatchMainAfter(delay: 2, block: {
                
                SVProgressHUD.dismiss()
            })
            
            print("加载异常")
        }
    }
    

//定时器
//    func monitoringPlayback()
//    {
//        self.player!.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 100), queue: DispatchQueue.main) {
//            
//            [unowned self] time in
//            
//            if UIApplication.shared.applicationState == .active {
//                
//                let items = self.playerItem!.duration.value
//                let miao = self.playerItem!.duration.timescale
////                let currnet = self.player!.currentTime()
////                print(currnet)
//                let currentTime = CMTimeGetSeconds(self.player!.currentTime())
//                
//                let totalTime = TimeInterval(items) / TimeInterval(miao)
//                let timeStr = "\(self.formatPlayTime(secounds: currentTime)) / \(self.formatPlayTime(secounds: totalTime))"
//
//                self.timeLable!.text = timeStr
//                self.slider?.value = Float(currentTime/totalTime)
//                
//            } else {
//                
//                
//            }
//    }
//}

    
    @objc func sliderTouchDown(slider:UISlider){
        
        self.player!.pause()
        print("按下")

    }
    @objc func sliderTouchUpOut(slider:UISlider){
        
        self.player!.play()
        print("抬起")
        
        
    }
    
    @objc func sliderChange(slider:UISlider){
        
        if self.player!.status == AVPlayerStatus.readyToPlay
        {
            let duration = slider.value * Float(CMTimeGetSeconds(self.player!.currentItem!.duration))
            let seekTime = CMTimeMake(Int64(duration), 1)
            // 指定视频位置
            self.player!.seek(to: seekTime, completionHandler: { (b) in
                
                
            })
        }
        
    }
 
    @objc func update()
    {
        let items = self.playerItem!.duration.value
        let miao = self.playerItem!.duration.timescale
//                        let currnet = self.player!.currentTime()
        //                print(currnet)
        let currentTime = CMTimeGetSeconds(self.player!.currentTime())
        
        let totalTime = TimeInterval(items) / TimeInterval(miao)
        let timeStr = "\(self.formatPlayTime(secounds: currentTime)) / \(self.formatPlayTime(secounds: totalTime))"
        
        self.timeLable!.text = timeStr
        self.slider?.value = Float(currentTime/totalTime)
    }
    
    func formatPlayTime(secounds:TimeInterval)->String{
        if secounds.isNaN{
            return "00:00"
        }
        let Min = Int(secounds / 60)
        let ss = Int(secounds)  //先转成整型才能取余
        let Sec = Int(ss % 60)
        return String(format: "%02d:%02d", Min, Sec)
    }

    deinit{
        
        self.removeRevce()
    }
    func removeRevce()
    {
        SVProgressHUD.dismiss()
        if superView != nil{
            
            superView?.removeFromSuperview()
            playerItem!.removeObserver(self, forKeyPath: "loadedTimeRanges")
            playerItem!.removeObserver(self, forKeyPath: "status")
        }
        
    }

    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
       
        self.link!.invalidate()
    }


    func dispatchMainAfter(delay:TimeInterval, block:@escaping () -> Void)
    {
        
        //let delayTime = dispatch_time ( dispatch_time_t(DISPATCH_TIME_NOW) ,  Int64 ( delay  *  Double ( NSEC_PER_SEC )))
        //dispatch_after ( delayTime , dispatch_get_main_queue ())  {
            block()
       // }
        
    }


}
